package cn.wp.product.service.impl;

import cn.wp.basic.service.impl.BaseServiceImpl;
import cn.wp.product.domain.Product;
import cn.wp.product.domain.ProductDetail;
import cn.wp.product.mapper.ProductDetailMapper;
import cn.wp.product.mapper.ProductMapper;
import cn.wp.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Override
    @Transactional
    public void add(Product product) {
        // 设置状态 默认不上架
        product.setState(0L);
        // 设置销售量0
        product.setSalecount(0L);
        // 先保存 返回新增数据的主键
        super.add(product);

        // 获取ProductDetail对象
        ProductDetail productDetail = product.getProductDetail();
        // 设置Product_id的值
        productDetail.setProduct_id(product.getId());
        // 再保存
        productDetailMapper.save(productDetail);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 先删除t_product_detail表中的数据
        productDetailMapper.delByProductId(id);
        // 再删除t_product表数据
        super.delete(id);
    }

    @Override
    @Transactional
    public void update(Product product) {
        super.update(product);
        ProductDetail productDetail = product.getProductDetail();
        productDetail.setProduct_id(product.getId());
        productDetailMapper.update(productDetail);
    }

    /**
     * 批量上架
     * @param ids
     */
    @Override
    @Transactional
    public void onSale(List<Long> ids) {
        productMapper.onSale(ids);
    }

    /**
     * 批量下架
     * @param ids
     */
    @Override
    @Transactional
    public void offSale(List<Long> ids) {
        productMapper.offSale(ids);
    }
}
